//
//  AIGirlAlbumViewController.swift
//  AIGirl
//
//  Created by Rae on 2024/1/30.
//

import UIKit
import JXBanner
import JXPageControl
import SnapKit

class AIGirlAlbumViewController: AIGirlBaseViewController {

    private var navView = AIGirlModelDetailNavView()
    private lazy var setButton = c_make_ex(UIButton.self)
        .text("Set As Background").color(.white).font(16.font_bold)
        .bgColor("#453381".toColor.alpha(0.4)).corner(20).end()
    private lazy var downButton = c_make_ex(UIButton.self)
        .image("AIGirl_Message_download").end()
    private lazy var animateView = c_make_ex(UIView.self).corner(20).end()
    private lazy var VIPImageView = c_make_ex(UIImageView.self)
        .image("AIGirl_Message_downloadVIP").end()
    private lazy var diamondImg = UIIconButton(style: .top(itemSpace: 0))
    private lazy var linearBanner: JXBanner = {[weak self] in
        let banner = JXBanner()
        banner.indentify = "linearBanner"
        banner.delegate = self
        banner.dataSource = self
        return banner
    }()
    
    var photoDtos = [AIGirlDiscoverDetailPicModel]() {
        didSet{
            navView.picTotal = photoDtos.count
            linearBanner.reloadView()
        }
    }
    var selIndex: Int = 0 {
        didSet{
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.linearBanner.scrollToIndex(self.selIndex, animated: false)
            }
        }
    }
    private var photoId = 0
    private var imageUrl: String = ""
    private var downLoadCoin: Int = 0
    
    init() {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews {
            linearBanner
            navView
            setButton
            downButton
            animateView
        }
        
        linearBanner.fillContainer()
        navView.leading(0).trailing(0).top(.statusHeight).height(45.0)
        setButton.leading(25).bottom(50).width(200).height(40)
        downButton.trailing(25).bottom(50).size(40)
        animateView.trailing(80).bottom(50).size(40)
        
        navView.isVip = false
        navView.backClosure = {
            self.dismissVC()
        }
        diamondImg.style { v in
            v.setImage("AIGirl_Message_diamond".toImage, for: .normal)
            v.iconSize = CGSize(width: 17, height: 17)
            v.setTitleColor(.white, for: .normal)
            v.titleLabel?.font = 10.font_semiBold
            v.backgroundColor = .black.alpha(0.09)
            v.layer.cornerRadius = 20
            v.layer.masksToBounds = true
            v.isUserInteractionEnabled = false
        }
        
        
        downButton.addTarget(self, action: #selector(clickDownloadButton), for: .touchUpInside)
        setButton.addTarget(self, action: #selector(clickSetButton), for: .touchUpInside)
        
        animateView.addSubview(VIPImageView)
        animateView.addSubview(diamondImg)
        VIPImageView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        diamondImg.frame = CGRect(x: 0, y: 40, width: 40, height: 40)
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(adjustFrames), userInfo: nil, repeats: true)
    }
    
    @objc func adjustFrames() {
            // 交换两个视图的 frame
        let tempFrame = VIPImageView.frame
        VIPImageView.frame = diamondImg.frame
        diamondImg.frame = tempFrame
    }
    
    @objc private func clickDownloadButton(){
        
        if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
            //会员直接下载
            downloadImage()
        }else {
            
            if GlobalTool.userModel?.money ?? 0 > downLoadCoin {
                downloadImage()
            }else {
                GlobalTool.showVipInfoPage()
            }
        }
    }
    @objc private func clickSetButton(){
        
        let girlId = UserDefaultsManager.getInt(forKey: .girlId)
        request.start(.saveChatBackground(girlId: girlId, photoId: photoId)) { result in
            if result.isSuccessful {
                "Successfully changed background".toast_success
                self.dismiss(animated: true)
            }
        }
    }
    
    @objc private func dismissVC(){
        self.dismiss(animated: true)
    }
    
    private func downloadImage(){
        
        request.start(.downloadPhoto(picId: photoId)) { result in
            if result.isSuccessful {
                self.downLoadImageToAlbum()
            }
        }
    }
    
    private func downLoadImageToAlbum(){
        ToastTool.show()
        let imageURL = URL(string: imageUrl)!
        // 创建一个 URLSession
        let session = URLSession(configuration: .default)

        // 创建一个下载任务
        let downloadTask = session.downloadTask(with: imageURL) { (url, response, error) in
            guard let url = url, error == nil else {
                // 处理错误
                print("下载图片出错：\(error?.localizedDescription ?? "未知错误")")
                "下载图片出错：\(error?.localizedDescription ?? "未知错误")".toast_error
                ToastTool.dismiss()
                return
            }

            do {
                // 将下载的图片数据读取为 Data
                let imageData = try Data(contentsOf: url)

                // 将 Data 转为 UIImage
                if let image = UIImage(data: imageData) {
                    // 将图片保存到相册
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    "Successfully downloaded".toast_success
                    print("图片保存成功")
                    ToastTool.dismiss()
                } else {
                    ToastTool.dismiss()
                    print("无法将数据转换为图片")
                }
            } catch {
                ToastTool.dismiss()
                print("读取图片数据失败：\(error.localizedDescription)")
            }
        }

        // 启动下载任务
        downloadTask.resume()
    }
}

extension AIGirlAlbumViewController: JXBannerDataSource, JXBannerDelegate {
    
    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return photoDtos.count
    }

    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {

        return JXBannerCellRegister(type: AIGirlModelDetailCell.self,
                                        reuseIdentifier: "FJBannerCell")
    }

    func jxBanner(_ banner: JXBannerType,
                  cellForItemAt index: Int,
                  cell: UICollectionViewCell) -> UICollectionViewCell {

        guard let imageCell = cell as? AIGirlModelDetailCell else {
            return cell
        }
        
        imageCell.model = photoDtos[index]
        return imageCell
    }

    func jxBanner(_ banner: JXBannerType,
                  params: JXBannerParams) -> JXBannerParams {

        return params
            .timeInterval(2)
            .cycleWay(.forward)
            .isAutoPlay(false)
    }
    
    // 最中心显示cell 索引
    func jxBanner(_ banner: JXBannerType, center index: Int) {
        
        self.navView.currentIndex = index + 1
        self.photoId = photoDtos[index].id
        self.imageUrl = photoDtos[index].image
        self.diamondImg.setTitle("\(photoDtos[index].downPrice)", for: .normal)
        self.downLoadCoin = photoDtos[index].downPrice
    }
}
